package club.pchome.service;

import club.pchome.constant.Constant;
import club.pchome.ex.ServiceException;
import club.pchome.ex.code.BaseResponseCode;
import club.pchome.mapper.UserMapper;
import club.pchome.model.User;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public User userInfo(int id){
        return userMapper.selectByPrimaryKey(id);
    }

    public int regUser(User user){
        String uuid = IdUtil.simpleUUID();
        user.setUid(uuid);
        user.setPasswd(DigestUtil.md5Hex(user.getPasswd() + Constant.MD5_USER_KEY));

        return userMapper.regUser(user);
    }

    public boolean isTrue(User user){
        return userMapper.isTrue(user);
    }

    public User loginUser(String username , String passwd, String ua) throws ServiceException {

        User user = userMapper.loginUser(username , passwd);

        if(user != null){
            User user1 = new User();
            user1.setId(user.getId());
            user1.setDevice(ua);

            int state = update(user1);
            if(state < 1){
                throw new ServiceException(BaseResponseCode.SYSTEM_UPDATE_ERROR);
            }
        }
        return user;
    }

    public int update(User user){
        return userMapper.updateByPrimaryKeySelective(user);
    }
}
